package internal

import (
	"fmt"
	"git.supremind.info/product/box/vehicle/common"
	"git.supremind.info/product/box/vehicle/internal/api"
	"git.supremind.info/product/box/vehicle/internal/api/vmr_client"
	"git.supremind.info/product/box/vehicle/internal/middleware"
	"git.supremind.info/product/box/vehicle/internal/wsserver"
	"github.com/gin-gonic/gin"
	"time"
)

func NewRouter() *gin.Engine {
	// 创建gin Engine实例
	r := gin.New()
	// 请求日志输出
	//r.Use(gin.Logger())
	r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))
	// 异常捕获处理
	r.Use(gin.Recovery())
	r.Use(costTimeMiddleware())

	// 创建路由处理实例
	schemaHistoryApi := api.SchemaHistory{}
	vehicleModelChemicalApi := api.NewVehicleModelChemicalApi()

	r.POST("/v1/app/auth/login", api.Login)
	r.GET("/v1/app/ws", wsserver.WsPing)

	// 添加路由组
	apiv1 := r.Group("/v1/app")
	apiv1.Use(common.LogerMiddleware())
	apiv1.Use(middleware.CheckJWTAuth())
	{
		apiv1.GET("/auth/logout", api.LogOut)
		apiv1.POST("/register", api.RegisterUser)
		apiv1.GET("/test", middleware.CheckJWTAuth(), api.GetDataByTime)
		//apiv1.GET("/ws", wsserver.WsPing)

		apiv1.GET("/box", vmr_client.QueryBoxInfo)
		apiv1.GET("/time/ntp", vmr_client.GetTimeNtp)
		apiv1.GET("/time/timezone/time", vmr_client.GetTimeZone)
		apiv1.GET("/time/timezone/list", vmr_client.GetTimeZoneList)

		// 车型识别接口
		apiv1.POST("/model/hisDataList", api.GetHisDataList)
		apiv1.DELETE("/model/delHisData", api.DelHisData)
		apiv1.GET("/model/consts", api.GetTypeConstList)
		apiv1.GET("/model/count", api.QueryCount)

		//保护性存储大小接口
		apiv1.POST("/vmr/model/system/storage", vmr_client.SystemsStorage)
		//查询盒子信息
		apiv1.GET("/vmr/model/boxInfo", vmr_client.QueryBoxInfo)
		//修改盒子信息
		apiv1.PUT("/vmr/model/updateBox", vmr_client.UpdateBox)
		//查询默认接口的ipv4地址和dns服务器
		apiv1.GET("/vmr/model/ipv4", vmr_client.QueryIpv4)
		//配置默认接口的ipv4地址和dns服务器, 执行成功会自动关闭dhcp
		apiv1.POST("/vmr/model/ipv4", vmr_client.UpdateIpv4)
		//设置摄像头
		apiv1.PUT("/vmr/model/camera/:location_type", vmr_client.SetCamera)
		//获取摄像头
		apiv1.GET("/vmr/model/camera", vmr_client.GetCamera)
		//获取摄像头状态
		apiv1.GET("/vmr/model/camera/status", vmr_client.GetCameraStatus)
		//设置车身任务
		apiv1.PUT("/vmr/model/task", vmr_client.SetTask)
		//获取车身任务
		apiv1.GET("/vmr/model/task", vmr_client.GetTask)
		//获取冗余信息
		apiv1.GET("/vmr/model/extra", vmr_client.GetExtraData)
		//设置冗余信息
		apiv1.PUT("/vmr/model/extra", vmr_client.SetExtraData)
		//获取车身摄像头配置
		apiv1.GET("/vmr/model/side_camera/config", vmr_client.GetSideCameraConfig)
		//设置车身摄像头配置
		apiv1.PUT("/vmr/model/side_camera/config", vmr_client.SideCameraConfig)
		//获取车身摄像头曝光值
		apiv1.GET("/vmr/model/side_camera/exposure", vmr_client.GetSideCameraExposure)
		//获取设备状态
		apiv1.GET("/vmr/model/service/status", vmr_client.GetDeviceStatus)
		//开启服务（进入运行状态）
		apiv1.GET("/vmr/model/service/start", vmr_client.StartService)
		//停止服务（进入配置状态）
		apiv1.GET("/vmr/model/service/stop", vmr_client.StopService)
		//获取车身相机抓拍图
		apiv1.POST("/vmr/model/side_camera/capture", vmr_client.GetSideCameraCapture)

		//查询默认接口的ipv4地址和dns服务器
		apiv1.GET("/network/option", api.NetworkOption)
		//若干network选项设置，接口会阻塞至配置生效或失败后返回
		apiv1.POST("/network/option", api.NetworkOption)

		apiv1.POST("/schemaHistory", schemaHistoryApi.Create)
		apiv1.POST("/collections", vehicleModelChemicalApi.Create)
		apiv1.GET("/getAllUsers", api.GetAllUser)

		//保存升级包信息
		apiv1.POST("/box/saveUpgradeDeb", api.SaveUpgradeDeb)
		//获取升级包列表
		apiv1.GET("/box/upgrade/version", api.GetUpgradeVersions)
		//删除升级包
		apiv1.DELETE("/box/upgrade/version", api.DeleteUpgradeVersion)
		//整包升级
		apiv1.POST("/box/upgrade", api.DoUpgrade)
		//sdk升级
		apiv1.POST("/box/upgradeSdk", api.DoSdkUpgrade)
		//升级记录
		apiv1.GET("/box/upgrade/log", api.GetUpgradeLogList)
	}
	return r
}

func costTimeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 请求前获取当前时间
		nowTime := time.Now()
		// 请求处理
		c.Next()
		// 请求处理完获取花费的时间
		costTime := time.Since(nowTime)
		requestURL := c.Request.URL.String()
		fmt.Printf("[the request URL] %s [cost] %v\n", requestURL, costTime)
	}
}
